package com.example.alipay_10_3.controller;

import cn.wooops.acp.sdk.AcpService;
import cn.wooops.acp.sdk.LogUtil;
import cn.wooops.acp.sdk.SDKConstants;
import com.example.alipay_10_3.Vo.Goods;
import com.example.alipay_10_3.Vo.Order;
import com.example.alipay_10_3.Vo.Price;
import com.example.alipay_10_3.server.PriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@CrossOrigin
public class PriceController {
    @Autowired
    private PriceService priceService;  //所有接口
    private String userid = "123456789";  //用户账号，全局变量

    //商品展示模块
    //展示所有商品
    @RequestMapping("/pricelist")
    @ResponseBody
    public List<Price> all(){
        List<Price> prices = priceService.select();
        return prices;
    }

    //按名称查找商品
    @RequestMapping("/searchbyname")
    @ResponseBody
    public List<Price> searchbyname(@RequestParam(value = "name") String name){
        List<Price> prices = priceService.findbyname(name);
        return prices;
    }

    //加入购物车
    @RequestMapping("/savetocart")
    @ResponseBody
    public void save(@RequestBody Goods goods){
        priceService.save(goods);
    }

    //购物车模块
    //展示购物车里的商品
    @RequestMapping("/goodscart")
    @ResponseBody
    public List<Goods> findallgoods(@RequestParam(value = "userid") String userid){
        List<Goods> goods = priceService.selectgoods(userid);
        return goods;
    }

    //删除购物车商品
    @RequestMapping("/deletefromcart")
    @ResponseBody
    public List<Goods> delete(@RequestParam(value = "userid") String userid,@RequestParam(value = "id") Integer id){
        priceService.deleteGoods(userid,id);
        List<Goods> goods = priceService.selectgoods(userid);
        return goods;
    }

    //清空购物车
    @RequestMapping("/deleteallgoods")
    @ResponseBody
    public List<Goods> deleteall(@RequestParam(value = "userid") String userid){
        priceService.deleteAllGoods(userid);
        List<Goods> goods = priceService.selectgoods(userid);
        return goods;
    }

    //订单管理模块
    //支付宝后台异步通知
    @RequestMapping("/alipayorderstorage")
    @ResponseBody
    public void aliorderstore(HttpServletRequest httpServletRequest) throws ParseException {
        Map<String,String> page = convertRequestToMap(httpServletRequest);
        Order order = new Order();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        order.setUserid(userid);
        order.setOrderid(page.get("out_trade_no"));
        order.setOrdername(page.get("buyer_id"));
        order.setOrderprice(Double.parseDouble(page.get("receipt_amount")));
        order.setOrderdate(new Timestamp(simpleDateFormat.parse(page.get("gmt_payment")).getTime()));
        order.setOrderpaytype("支付宝");
        priceService.orderstorage(order);
    }

    //银联后台异步通知
    @RequestMapping("/unionpayorderstorage")
    @ResponseBody
    public void unionorderstore(HttpServletRequest httpServletRequest) throws ParseException {
        String encoding = httpServletRequest.getParameter(SDKConstants.param_encoding);
        Map<String,String> page = getAllRequestParam(httpServletRequest);
        Order order = new Order();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        if (!AcpService.validate(page, encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            //验签失败，需解决验签问题

        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            //【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态
            order.setUserid(userid);
            order.setOrderid(page.get("orderId"));
            order.setOrdername(page.get("accNo"));
            order.setOrderprice(Double.parseDouble(page.get("txnAmt"))/100);
            order.setOrderdate(new Timestamp(simpleDateFormat.parse(page.get("txnTime")).getTime()));
            order.setOrderpaytype("银联");
            priceService.orderstorage(order);
        }
    }

    //银联前台同步通知
    @RequestMapping("/returnhome")
    @ResponseBody
    public void returntohome(HttpServletResponse resp) throws IOException{
        String url = "http://hello.free.svipss.top/";
        resp.sendRedirect(url);
    }

    //将支付宝回调request信息映射到Map上
    private static Map<String, String> convertRequestToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

    //将银联回调request信息映射到Map上
    private Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                if (res.get(en) == null || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

    //显示用户所有订单信息
    @RequestMapping("/orderlist")
    @ResponseBody
    public List<Order> orderreturn(@RequestParam(value = "userid") String userid){
        List<Order> order = priceService.orderList(userid);
        return order;
    }

    //查找用户订单信息
    @RequestMapping("/ordersearch")
    @ResponseBody
    public List<Order> searchorder(@RequestParam(value = "userid") String userid,@RequestParam(value = "startdate") Timestamp start,@RequestParam(value = "enddate") Timestamp end){
        List<Order> order = priceService.findOrder(userid,start,end);
        return order;
    }

    //thymeleaf测试
    @RequestMapping("/pricelook")
    public String alllook(Model model){
        List<Price> prices = priceService.select();
        model.addAttribute("prices",prices);
        return "price_list";
    }

    //测试代码（可以自己按需编写）
    @RequestMapping("/test")
    public void test(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        LogUtil.writeLog("FrontRcvResponse前台接收报文返回开始");

        String encoding = req.getParameter(SDKConstants.param_encoding);

        LogUtil.writeLog("返回报文中encoding=[" + encoding + "]");

        String pageResult = "";

        Map<String, String> respParam = getAllRequestParam(req);

        StringBuffer page = new StringBuffer();

        LogUtil.printRequestLog(respParam);

        if (!AcpService.validate(respParam, encoding)) {

            LogUtil.writeLog("验证签名结果[失败].");

        } else {

            LogUtil.writeLog("验证签名结果[成功].");


            String accNo = respParam.get("accNo");

            System.out.println("未解密的卡号："+accNo);

//如果返回的卡号是密文那么，可以用下边方法解密

            if(null!=accNo){

                accNo = AcpService.decryptData(accNo, "UTF-8");

                page.append("<br>accNo明文: "+accNo);

            }

            System.out.println("已解密的卡号："+accNo);
//判断respCode=00、A6后，对涉及资金类的交易，请再发起查询接口查询，确定交易成功后更新数据库。

        }


        req.setAttribute("result", page.toString());

        req.getRequestDispatcher(pageResult).forward(req, resp);


        LogUtil.writeLog("FrontRcvResponse前台接收报文返回结束");
    }
}
